import re
import matplotlib.pyplot as plt
from collections import defaultdict
from typing import Dict, List, TypedDict
import os
import matplotlib

# 设置中文字体
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False


class Forecast(TypedDict):
    day: str
    weather: str
    temp_high: int
    temp_low: int
    wind: str


class City(TypedDict):
    name: str
    code: str
    forecasts: List[Forecast]


def parse_weather_data(file_path: str) -> List[City]:
    """解析天气数据文件"""
    cities = []
    current_city = None

    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if line.startswith('===') and line.endswith('==='):
                # 新城市开始
                if current_city:
                    cities.append(current_city)

                city_info = line[4:-4].split('(')
                name = city_info[0].strip()
                code = city_info[1].split(':')[1].split(')')[0].strip()
                current_city = {'name': name, 'code': code, 'forecasts': []}
            elif current_city and ':' in line:
                # 解析天气数据
                parts = line.split(':')
                day = parts[0].strip()
                weather_info = parts[1].split(',')
                weather = weather_info[0].strip()
                temp = weather_info[1].strip()
                wind = weather_info[2].strip()

                # 处理温度
                if '/' in temp:
                    temp_high, temp_low = map(int, temp.replace('℃', '').split('/'))
                else:
                    temp_high = temp_low = int(temp.replace('℃', ''))

                current_city['forecasts'].append({
                    'day': day,
                    'weather': weather,
                    'temp_high': temp_high,
                    'temp_low': temp_low,
                    'wind': wind
                })

    if current_city:
        cities.append(current_city)
    return cities


def analyze_weather(cities: List[City]) -> Dict[str, Dict]:
    """分析天气数据"""
    results = {
        'temperature_stats': {},
        'weather_distribution': defaultdict(int),
        'wind_distribution': defaultdict(int)
    }

    for city in cities:
        temps = []
        weathers = []
        winds = []

        for forecast in city['forecasts']:
            temps.append(forecast['temp_high'])
            temps.append(forecast['temp_low'])
            weathers.append(forecast['weather'])
            winds.append(forecast['wind'])

        # 计算温度统计
        results['temperature_stats'][city['name']] = {
            'max': max(temps),
            'min': min(temps),
            'avg': round(sum(temps) / len(temps), 1)
        }

        # 统计天气和风力分布
        for weather in weathers:
            results['weather_distribution'][weather] += 1
        for wind in winds:
            results['wind_distribution'][wind] += 1

    return results


def save_text_results(results: Dict[str, Dict], output_path: str) -> None:
    pass


def generate_html_report(results: Dict[str, Dict], output_dir: str) -> None:
    """生成HTML格式的分析报告"""
    html_path = os.path.join(output_dir, 'analysis_report.html')

    # 生成温度对比图
    temp_stats = results['temperature_stats']
    cities = list(temp_stats.keys())
    max_temps = [temp_stats[city]['max'] for city in cities]
    avg_temps = [temp_stats[city]['avg'] for city in cities]
    min_temps = [temp_stats[city]['min'] for city in cities]

    temp_chart_path = os.path.join(output_dir, 'temperature_comparison.png')
    plt.figure(figsize=(16, 8))
    x = range(len(cities))
    width = 0.25
    plt.bar([i - width for i in x], max_temps, width, label='最高温度')
    plt.bar(x, avg_temps, width, label='平均温度')
    plt.bar([i + width for i in x], min_temps, width, label='最低温度')
    plt.xlabel('城市', fontsize=12)
    plt.ylabel('温度(℃)', fontsize=12)
    plt.title('城市温度对比', fontsize=14)
    plt.xticks(x, [name[:4] + '..' if len(name) > 6 else name for name in cities],
               rotation=45, fontsize=10)
    plt.yticks(fontsize=10)
    plt.legend(fontsize=8, bbox_to_anchor=(1.02, 1), loc='upper left')
    plt.subplots_adjust(bottom=0.25, right=0.85)
    plt.grid(axis='y', linestyle='--', alpha=0.7)
    plt.savefig(temp_chart_path, dpi=300, bbox_inches='tight', facecolor='white')
    plt.close()

    # 生成天气分布图
    weather_dist = results['weather_distribution']
    weather_chart_path = os.path.join(output_dir, 'weather_distribution.png')
    plt.figure(figsize=(12, 6))
    plt.bar(weather_dist.keys(), weather_dist.values())
    plt.xlabel('天气状况', fontsize=12)
    plt.ylabel('出现次数', fontsize=12)
    plt.title('天气状况分布', fontsize=14)
    plt.xticks(rotation=45, fontsize=10)
    plt.yticks(fontsize=10)
    plt.tight_layout()
    plt.savefig(weather_chart_path, dpi=300, facecolor='white')
    plt.close()

    # 生成HTML内容
    html_content = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>城市天气分析报告</title>
    <style>
        body {{ font-family: 'Microsoft YaHei', sans-serif; margin: 20px; }}
        h1 {{ color: #333; }}
        .section {{ margin-bottom: 30px; }}
        .chart {{ text-align: center; margin: 20px 0; }}
        table {{ border-collapse: collapse; width: 100%; margin-bottom: 20px; }}
        th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
        th {{ background-color: #f2f2f2; }}
    </style>
</head>
<body>
    <h1>城市天气分析报告</h1>

    <div class="section">
        <h2>温度统计</h2>
        <div class="chart">
            <img src="temperature_comparison.png" alt="温度对比图" style="max-width: 100%;">
        </div>
        <table>
            <tr>
                <th>城市</th>
                <th>最高温度(℃)</th>
                <th>平均温度(℃)</th>
                <th>最低温度(℃)</th>
            </tr>
            {"".join(f'''
            <tr>
                <td>{city}</td>
                <td>{stats['max']}</td>
                <td>{stats['avg']}</td>
                <td>{stats['min']}</td>
            </tr>
            ''' for city, stats in results['temperature_stats'].items())}
        </table>
    </div>

    <div class="section">
        <h2>天气状况分布</h2>
        <div class="chart">
            <img src="weather_distribution.png" alt="天气分布图" style="max-width: 100%;">
        </div>
        <table>
            <tr>
                <th>天气状况</th>
                <th>出现次数</th>
            </tr>
            {"".join(f'''
            <tr>
                <td>{weather}</td>
                <td>{count}</td>
            </tr>
            ''' for weather, count in results['weather_distribution'].items())}
        </table>
    </div>
</body>
</html>
    """

    with open(html_path, 'w', encoding='utf-8') as f:
        f.write(html_content)


def save_results(results: Dict[str, Dict], output_path: str) -> None:
    output_dir = os.path.dirname(output_path)

    # 保存文本结果
    save_text_results(results, output_path)

    # 生成HTML报告
    generate_html_report(results, output_dir)


if __name__ == "__main__":
    input_path = 'weather.txt'
    output_path = 'analysis_results.txt'
    cities = parse_weather_data(input_path)
    analysis = analyze_weather(cities)
    save_results(analysis, output_path)
    print(f"分析完成，结果已保存到{output_path}和analysis_report.html")
